package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.utils.ExcelExportUtils;
import com.rockcent.common.utils.RDateFormatUtils;
import com.rockcent.common.utils.RDateUtils;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.MallFund;
import com.rockcent.mall.lib.domain.MallFundFlow;
import com.rockcent.mall.lib.domain.enumclass.FundTransactionFlow;
import com.rockcent.mall.lib.domain.enumclass.MallFundFlowTransactionType;
import com.rockcent.mall.lib.domain.enumclass.PaymentMethod;
import com.rockcent.mall.lib.dto.MallFundFlowDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.MallFundFlowRepository;
import com.rockcent.mall.lib.repository.MallFundRepository;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by DK on 16/11/8.
 * 平台资金
 */
@RestController
public class MallFundFlowController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallFundFlowController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private MallFundRepository mallFundRepository;

    @Autowired
    private MallFundFlowRepository mallFundFlowRepository;

    /**
     * @api {get} /mall/fund/info 平台账户详情
     * @apiGroup MALL_FUND
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {BigDecimal} totalAmount 总金额
     * @apiSuccess {BigDecimal} frozen 冻结金额
     * @apiSuccess {BigDecimal} availableCashAmount 可用现金券金额
     * @apiSuccess {BigDecimal} availableAmount 可用金额
     * @apiSuccess {Long} mallId 平台ID
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "lastUpdated": "2016-08-11 16:27:32",
     *      "dateCreated": "2016-08-11 16:27:32",
     *      "totalAmount": 3242,
     *      "frozen": 222,
     *      "availableCashAmount": 222,
     *      "availableAmount": 288,
     *      "mallId": 1
     *  }
     * }
     */
    @RequestMapping(value = Routes.MALL_FUND_INFO, method = RequestMethod.GET)
    public JsonResult mallFundInfo(HttpServletRequest request){
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            MallFund mallFund = mallFundRepository.findByMallId(userDto.mall.getId());
            jsonResult.data = mallFund;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/fund/flow/page 平台资金流水分页
     * @apiGroup MALL_FUND
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String=ALL("全部"), INCOME("收入"), EXPEND("支出")} transactionFlow <code>必传参数</code> 收支种类
     * @apiParam {String=ALL("全部"), BALANCE("余额支付"), WECHAT("微信支付"), CASH_COUPON("现金券")} paymentMethod <code>必传参数</code> 支付方式
     * @apiParam {String=ALL("全部"), F_PAYMENT_SUCCESS_FROZEN("订单收入"),F_CASH_COUPON_SURPLUS_SUCCESS_FROZEN_INCOME("现金券余额订单收入"), A_SERVICE_FEE("服务费收入"), F_MERCHANT_SETTLEMENT("商家货款"), RESELL_FEE_EXPEND("分销佣金"), SHARER_FEE_EXPEND("分享者返利"), BUYER_FEE_EXPEND("购买者分享返利"),MERCHANT_SERVICE_FEE_INCOME("商户基础服务费收入")} transactionType <code>必传参数</code> 交易类型
     * @apiParam {Double} operationAmount 收入金额
     * @apiParam {String} beginDate 开始时间
     * @apiParam {String} endDate 结束时间
     * @apiParam {String} mallOrderNum 订单号
     *
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {BigDecimal} totalAmount 账户总余额
     * @apiSuccess {BigDecimal} frozen 冻结金额
     * @apiSuccess {BigDecimal} operationAmount 收入金额
     * @apiSuccess {BigDecimal} availableAmount 账户余额
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} mallFundId 平台账户ID
     * @apiSuccess {String=INCOME("收入"), EXPEND("支出")} transactionType 收支种类
     * @apiSuccess {String=F_PAYMENT_SUCCESS_FROZEN("订单收入"), A_SERVICE_FEE("服务费收入"), F_MERCHANT_SETTLEMENT("商家货款"), RESELL_FEE_EXPEND("分销佣金"), SHARER_FEE_EXPEND("分享者返利"), BUYER_FEE_EXPEND("购买者分享返利"), F_CASH_COUPON_SURPLUS_SUCCESS_INCOME("现金券余额收入"),F_CASH_COUPON_SURPLUS_SUCCESS_FROZEN_INCOME("订单收入"), F_BALANCE_SUCCESS_FROZEN("订单收入")} transactionFlow 交易类型
     * @apiSuccess {String=BALANCE("余额支付"), WECHAT("微信支付"), CASH_COUPON("现金券")} paymentMethod 支付方式
     * @apiSuccess {String} remark 备注
     * @apiSuccess {String} mallOrderNum 平台订单号
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "data": [
     *           {
     *           "id": 3,
     *           "dateCreated": "2016-11-08 15:39:10",
     *           "lastUpdated": "2016-11-08 15:39:10",
     *           "mallOrderNum": "201611081542085463832282",
     *           "totalAmount": 192,
     *           "frozen": 288,
     *           "availableAmount": 0,
     *           "remark": "用户支付成功冻结金额 订单收入",
     *           "operationAmount": 96,
     *           "transactionFlow": "INCOME",
     *           "transactionType": "F_PAYMENT_SUCCESS_FROZEN",
     *           "paymentMethod": "BALANCE",
     *           "mallFundId": 1,
     *           "mallId": 1
     *           },
     *           .....
     *       ]
     *  }
     * }
     */
    @RequestMapping(value = Routes.MALL_FUND_FLOW_PAGE, method = RequestMethod.GET)
    public JsonResult mallFundFlowPage(HttpServletRequest request, MallFundFlowDto dto){
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getTransactionFlow()) || !EnumUtils.isValidEnum(FundTransactionFlow.class, dto.getTransactionFlow())){
                jsonResult.remind("交易类型只允许 ALL(\"全部\"), INCOME(\"收入\"), EXPEND(\"支出\")",log);
                return;
            }
            if (StringUtils.isBlank(dto.getTransactionType()) || !EnumUtils.isValidEnum(MallFundFlowTransactionType.class, dto.getTransactionType())) {
                jsonResult.remind("收支种类只允许 ALL(\"全部\"), F_PAYMENT_SUCCESS_FROZEN(\"订单收入\"), A_SERVICE_FEE(\"服务费收入\"), F_MERCHANT_SETTLEMENT(\"商家货款\"), RESELL_FEE_EXPEND(\"分销佣金\"), SHARER_FEE_EXPEND(\"分享者返利\"), BUYER_FEE_EXPEND(\"购买者分享返利\")",log);
                return;
            }
            if (StringUtils.isBlank(dto.getPaymentMethod()) || !EnumUtils.isValidEnum(PaymentMethod.class, dto.getPaymentMethod())) {
                jsonResult.remind("支付类型只允许 ALL(\"全部\"), BALANCE(\"余额支付\"), WECHAT(\"微信支付\"), CASH_COUPON(\"现金券\")",log);
                return;
            }
            PageResult<MallFundFlowDto> pageResult = mallFundFlowRepository.findMallFundFlowPage(dto.getTransactionType(), dto.getTransactionFlow(), dto.getPaymentMethod(), dto.getBeginDate(), dto.getEndDate(), dto.getOperationAmount(), dto.getMallOrderNum(), userDto.mall.getId(), this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.MALL_FUND_FLOW_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/fund/expend/info/flow 平台资金支出拆分详情
     * @apiGroup MALL_FUND
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id 流水ID
     *
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {BigDecimal} operationAmount 操作金额
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {String=A_SERVICE_FEE("服务费收入"), RESELL_FEE_EXPEND("分销佣金"), SHARER_FEE_EXPEND("分享者返利"), BUYER_FEE_EXPEND("购买者分享返利"), F_MERCHANT_SETTLEMENT("商家订单收入")} transactionType 收支种类
     * @apiSuccess {String} remark 备注
     * @apiSuccess {String} mallOrderNum 平台订单号
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "data": [
     *           {
     *           "id": 3,
     *           "dateCreated": "2016-11-08 15:39:10",
     *           "lastUpdated": "2016-11-08 15:39:10",
     *           "mallOrderNum": "201611081542085463832282",
     *           "operationAmount": 96,
     *           "transactionType": "F_PAYMENT_SUCCESS_FROZEN",
     *           "paymentMethod": "CASH_COUPON",
     *           "mallId": 1
     *           },
     *           .....
     *       ]
     *  }
     * }
     */
    @RequestMapping(value = Routes.MALL_FUND_EXPEND_INFO_FLOW, method = RequestMethod.GET)
    public JsonResult mallFundExpendInfoFlow(HttpServletRequest request, MallFundFlowDto dto){
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MallFundFlow.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            List<MallFundFlowDto> mallFundExpendInfoFlowList = mallFundFlowRepository.findByParentIdAndMallIdAndTransactionFlow(dto.getId(), userDto.mall.getId(), FundTransactionFlow.SPLIT);
            jsonResult.data = mallFundExpendInfoFlowList;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/fund/flow/export 平台资金流水资金报表excel导出
     * @apiGroup MALL_FUND
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String=ALL("全部"), INCOME("收入"), EXPEND("支出")} transactionFlow <code>必传参数</code> 收支种类
     * @apiParam {String=ALL("全部"), BALANCE("余额支付"), WECHAT("微信支付"), CASH_COUPON("现金券")} paymentMethod <code>必传参数</code> 支付方式
     * @apiParam {String=ALL("全部"), F_PAYMENT_SUCCESS_FROZEN("订单收入"), A_SERVICE_FEE("服务费收入"), F_MERCHANT_SETTLEMENT("商家货款"), RESELL_FEE_EXPEND("分销佣金"), SHARER_FEE_EXPEND("分享者返利"), BUYER_FEE_EXPEND("购买者分享返利")} transactionType <code>必传参数</code> 交易类型
     * @apiParam {Double} operationAmount 收入金额
     * @apiParam {String} beginDate 开始时间
     * @apiParam {String} endDate 结束时间
     * @apiParam {String} mallOrderNum 订单号
     *
     * @apiSuccessExample { json } Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功"
     *  }
     */
    @RequestMapping(value = Routes.MALL_FUND_FLOW_EXPORT, method = RequestMethod.GET)
    public JsonResult mallFundFlowExport(HttpServletRequest request, HttpServletResponse response, MallFundFlowDto dto) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            //默认查询时间为近一个月
            if (StringUtils.isBlank(dto.getBeginDate())) {
                dto.setBeginDate(RDateFormatUtils.formatParseDatePattern(RDateUtils.beforeDate(30)));
                dto.setEndDate(RDateFormatUtils.formatParseDatePattern(new Date()));
            }
            if (StringUtils.isBlank(dto.getTransactionFlow()) || !EnumUtils.isValidEnum(FundTransactionFlow.class, dto.getTransactionFlow())){
                jsonResult.remind("交易类型只允许 ALL(\"全部\"), INCOME(\"收入\"), EXPEND(\"支出\")",log);
                return;
            }
            if (StringUtils.isBlank(dto.getTransactionType()) || !EnumUtils.isValidEnum(MallFundFlowTransactionType.class, dto.getTransactionType())) {
                jsonResult.remind("收支种类只允许 ALL(\"全部\"), F_PAYMENT_SUCCESS_FROZEN(\"订单收入\"), A_SERVICE_FEE(\"服务费收入\"), F_MERCHANT_SETTLEMENT(\"商家货款\"), RESELL_FEE_EXPEND(\"分销佣金\"), SHARER_FEE_EXPEND(\"分享者返利\"), BUYER_FEE_EXPEND(\"购买者分享返利\")",log);
                return;
            }
            if (StringUtils.isBlank(dto.getPaymentMethod()) || !EnumUtils.isValidEnum(PaymentMethod.class, dto.getPaymentMethod())) {
                jsonResult.remind("支付类型只允许 ALL(\"全部\"), BALANCE(\"余额支付\"), WECHAT(\"微信支付\"), CASH_COUPON(\"现金券\")",log);
                return;
            }
            List<MallFundFlowDto> mallFundFlowDtoList = mallFundFlowRepository.findMallFundFlowExport(dto.getTransactionType(), dto.getTransactionFlow(), dto.getPaymentMethod(), dto.getBeginDate(), dto.getEndDate(), dto.getOperationAmount(), dto.getMallOrderNum(), userDto.mall.getId());
            mallFundFlowDtoList.stream().map(mallFundFlow -> {
                if (FundTransactionFlow.EXPEND == FundTransactionFlow.valueOf(mallFundFlow.getTransactionFlow())) {
                    mallFundFlow.setActualAmount("-" + mallFundFlow.getOperationAmount());
                }
                if (FundTransactionFlow.INCOME == FundTransactionFlow.valueOf(mallFundFlow.getTransactionFlow())) {
                    mallFundFlow.setActualAmount("+" + mallFundFlow.getOperationAmount());
                }
                mallFundFlow.setTransactionType(MallFundFlowTransactionType.valueOf(mallFundFlow.getTransactionType()).getValue());
                return mallFundFlow;
            }).collect(Collectors.toList());

            String[] title = {"时间", "收支类型", "收支类型", "订单号", "收支金额", "账户总余额"};
            String[] columnName = {"createDate", "transactionType", "paymentMethod", "mallOrderNum", "actualAmount", "totalAmount"};
            //excel报表导出
            ExcelExportUtils.excelExport(title, columnName, mallFundFlowDtoList, response);
        };
        return doing.go(request, log);
    }
}
